#!/usr/bin/env bash
export PLATFORM="${PLATFORM:-$(uname -p)}"
export BUILDTOOL="build --platform=${PLATFORM}"
export RUN_OPTIONS="--platform=${PLATFORM}"
export PHP_VERSION=${PHP_VERSION:-8.3}
export BRANCH=${BRANCH:-v4}
export VARIANT=${VARIANT:-apache}
export BRANCH_VARIANT="${VARIANT//./-}"
export REPO="${REPO:-thecodingmachine/php}"
export TAG_PREFIX="${TAG_PREFIX:-}"
export SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

function unused_port() {
    N=${1:-1}
    comm -23 \
        <(seq "1025" "65535" | sort) \
        <(ss -Htan |
            awk '{print $4}' |
            cut -d':' -f2 |
            sort -u) |
        shuf |
        head -n "$N"
}

function waitfor() {
    URL=${1}
    TIMEOUT=${2:-60}
    while ! curl -sq "${URL}" > /dev/null 2>&1; do
      TIMEOUT=$((TIMEOUT-=1))
      if [[ "${TIMEOUT}" -lt "1" ]]; then
        >&2 echo "Can not fetch ${URL}"
        return 1
      fi
      sleep 1
    done
    return 0
}